<template>
  <div class="admin-profile">
    <div class="profile-header">
      <h2>个人信息</h2>
    </div>

    <el-tabs v-model="activeTab" class="profile-tabs">
      <!-- 基本信息 -->
      <el-tab-pane label="基本信息" name="basic">
        <el-form :model="profileForm" :rules="profileRules" ref="profileFormRef" label-width="100px" class="profile-form">
          <el-form-item label="头像">
            <div class="avatar-upload">
              <el-avatar :size="80" :src="profileForm.avatarUrl" class="avatar-preview">
                {{ getUserInitial() }}
              </el-avatar>
              <div class="upload-actions">
                <el-upload
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :http-request="handleAvatarUpload"
                  accept="image/*"
                >
                  <el-button type="primary" size="small" :loading="uploadLoading">
                    {{ profileForm.avatarUrl ? '更换头像' : '上传头像' }}
                  </el-button>
                </el-upload>
                <el-button 
                  v-if="profileForm.avatarUrl" 
                  type="danger" 
                  size="small" 
                  plain
                  @click="handleRemoveAvatar"
                  style="margin-left: 10px"
                >
                  删除头像
                </el-button>
              </div>
            </div>
          </el-form-item>
          
          <el-form-item label="用户名">
            <el-input v-model="profileForm.username" disabled />
          </el-form-item>
          
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="profileForm.nickname" placeholder="请输入昵称" />
          </el-form-item>
          
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
          </el-form-item>

          <el-form-item label="角色">
            <el-tag type="success">{{ profileForm.role === 'admin' ? '管理员' : '普通用户' }}</el-tag>
          </el-form-item>

          <el-form-item label="注册时间">
            <span>{{ formatDate(profileForm.createdAt) }}</span>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleUpdateProfile" :loading="updateLoading">
              保存修改
            </el-button>
            <el-button @click="loadProfile">取消</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 修改密码 -->
      <el-tab-pane label="修改密码" name="password">
        <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px" class="profile-form">
          <el-form-item label="原密码" prop="oldPassword">
            <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码" show-password />
          </el-form-item>
          
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码（至少6位）" show-password />
          </el-form-item>
          
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleChangePassword" :loading="passwordLoading">
              修改密码
            </el-button>
            <el-button @click="resetPasswordForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAdminProfile, updateAdminProfile, changeAdminPassword } from '../api/user'
import { uploadAvatar } from '../api/upload'

const activeTab = ref('basic')
const profileFormRef = ref(null)
const passwordFormRef = ref(null)
const updateLoading = ref(false)
const passwordLoading = ref(false)
const uploadLoading = ref(false)

// 个人资料表单
const profileForm = reactive({
  id: null,
  username: '',
  nickname: '',
  email: '',
  avatarUrl: '',
  role: '',
  createdAt: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const profileRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 加载个人资料
const loadProfile = async () => {
  try {
    const res = await getAdminProfile()
    if (res.code === 200) {
      Object.assign(profileForm, res.data)
    } else {
      ElMessage.error(res.msg || '获取个人资料失败')
    }
  } catch (error) {
    console.error('获取个人资料失败:', error)
    ElMessage.error('获取个人资料失败')
  }
}

// 更新个人资料
const handleUpdateProfile = async () => {
  if (!profileFormRef.value) return
  
  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      updateLoading.value = true
      try {
        const res = await updateAdminProfile({
          nickname: profileForm.nickname,
          email: profileForm.email,
          avatarUrl: profileForm.avatarUrl
        })
        
        if (res.code === 200) {
          ElMessage.success('更新成功')
          // 更新 localStorage 中的用户信息
          const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
          userInfo.nickname = profileForm.nickname
          userInfo.email = profileForm.email
          userInfo.avatarUrl = profileForm.avatarUrl
          localStorage.setItem('userInfo', JSON.stringify(userInfo))
          
          // 刷新页面以更新头部显示
          setTimeout(() => {
            window.location.reload()
          }, 1000)
        } else {
          ElMessage.error(res.msg || '更新失败')
        }
      } catch (error) {
        console.error('更新失败:', error)
        ElMessage.error('更新失败')
      } finally {
        updateLoading.value = false
      }
    }
  })
}

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordLoading.value = true
      try {
        const res = await changeAdminPassword({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })
        
        if (res.code === 200) {
          ElMessage.success('密码修改成功，请重新登录')
          resetPasswordForm()
          // 清除登录信息，跳转到登录页
          setTimeout(() => {
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
            window.location.href = '/login'
          }, 1500)
        } else {
          ElMessage.error(res.msg || '密码修改失败')
        }
      } catch (error) {
        console.error('密码修改失败:', error)
        ElMessage.error('密码修改失败')
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  if (passwordFormRef.value) {
    passwordFormRef.value.clearValidate()
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  const d = new Date(date)
  return d.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取用户名首字母
const getUserInitial = () => {
  const username = profileForm.username || profileForm.nickname || '管理员'
  return username.charAt(0).toUpperCase()
}

// 上传前验证
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 自定义上传
const handleAvatarUpload = async (options) => {
  uploadLoading.value = true
  try {
    // 1. 先上传文件
    const uploadRes = await uploadAvatar(options.file)
    if (uploadRes.code === 200) {
      profileForm.avatarUrl = uploadRes.data.url
      
      // 2. 立即保存到数据库
      const updateRes = await updateAdminProfile({
        nickname: profileForm.nickname,
        email: profileForm.email,
        avatarUrl: uploadRes.data.url
      })
      
      if (updateRes.code === 200) {
        ElMessage.success('头像上传并保存成功')
        
        // 3. 更新 localStorage 中的用户信息
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        userInfo.avatarUrl = uploadRes.data.url
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        
        // 4. 刷新页面以更新头部显示
        setTimeout(() => {
          window.location.reload()
        }, 1000)
      } else {
        ElMessage.error(updateRes.msg || '保存失败')
      }
    } else {
      ElMessage.error(uploadRes.msg || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  } finally {
    uploadLoading.value = false
  }
}

// 删除头像
const handleRemoveAvatar = () => {
  ElMessageBox.confirm('确认删除头像吗？', '删除确认', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 保存到数据库
      const updateRes = await updateAdminProfile({
        nickname: profileForm.nickname,
        email: profileForm.email,
        avatarUrl: null
      })
      
      if (updateRes.code === 200) {
        profileForm.avatarUrl = ''
        ElMessage.success('头像已删除')
        
        // 更新 localStorage
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        userInfo.avatarUrl = null
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        
        // 刷新页面
        setTimeout(() => {
          window.location.reload()
        }, 1000)
      } else {
        ElMessage.error(updateRes.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消
  })
}

onMounted(() => {
  loadProfile()
})
</script>

<style scoped>
.admin-profile {
  padding: 24px;
}

.profile-header {
  margin-bottom: 24px;
}

.profile-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.profile-tabs {
  background: white;
  padding: 20px;
  border-radius: 8px;
}

.profile-form {
  max-width: 600px;
  margin-top: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #f5f7fa;
  color: #909399;
}

.avatar-upload {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-preview {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: bold;
  font-size: 32px;
  flex-shrink: 0;
}

.upload-actions {
  display: flex;
  align-items: center;
}
</style>
